package com.llyb.filter;

import io.micrometer.common.util.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    // 过滤器优先级：自定义>默认>路由
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpCookie name = exchange.getRequest().getCookies().getFirst("name");

        if (!ObjectUtils.isEmpty(name)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        Mono<Void> mono = chain.filter(exchange);
        System.out.println("异步请求");
        // 请求结束执行的方法
        /*Mono<Void> mono = chain.filter(exchange).then(Mono.fromRunnable(() -> {
            System.out.println("请求后");
        }));*/

        return mono;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
